package cn.shiwei.hr.service.impl;

import cn.shiwei.hr.constants.BaseConstants;
import cn.shiwei.hr.doc.CourseDoc;
import cn.shiwei.hr.domain.*;
import cn.shiwei.hr.dto.CourseDto;
import cn.shiwei.hr.fegin.search.SearchFeginClient;
import cn.shiwei.hr.mapper.CourseMapper;
import cn.shiwei.hr.repository.AjaxResult;
import cn.shiwei.hr.service.ICourseDetailService;
import cn.shiwei.hr.service.ICourseMarketService;
import cn.shiwei.hr.service.ICourseService;
import cn.shiwei.hr.service.ICourseTypeService;
import cn.shiwei.hr.repository.AssertUtil;
import cn.shiwei.hr.to.SMSTO;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static cn.shiwei.hr.constants.BaseConstants.course.*;
import static cn.shiwei.hr.constants.BaseConstants.course.COURSE_IS_ON_THE_SHELF;
import static cn.shiwei.hr.constants.MessageConstants.EXCHANGE_NAME_TOPIC;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 1363732197@qq.com
 * @since 2021-11-26
 */
@Service
@Transactional
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private ICourseDetailService detailService;

    @Autowired
    private ICourseMarketService marketService;

    @Autowired
    private ICourseTypeService typeService;

    @Autowired
    private SearchFeginClient searchFeginClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public void updateByIdToDto(CourseDto courseDto) {
        super.updateById(courseDto.getCourse());
    }

    @Override
    public void insertToDto(CourseDto courseDto) {
        //TODO  此处搞个context, 获取login, 还要给login添字段,
        Login login = (Login)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Course course = courseDto.getCourse();
        CourseDetail courseDetail = courseDto.getCourseDetail();
        CourseMarket courseMarket = courseDto.getCourseMarket();

        course.setStatus(COURSE_IS_NOT_ON_THE_SHELF);
        // 假数据
        course.setTenantId(login.getTenantId());
        course.setTenantName(login.getTenantName());
        //
        course.setUserId(login.getId());
        course.setUserName(login.getUsername());

        Long id = course.getId();
        // 保存
        super.insert(course);
        // 课程和课程详情是一对一
        courseDetail.setId(id);
        detailService.insert(courseDetail);
        courseMarket.setId(id);
        marketService.insert( courseMarket);

    }

    @Override
    public void onLineCourse(Long id) {

        // 根据课程id 修改数据库中的上限状态(如果是已上架, 不管)
        Course course = baseMapper.selectById(id);
        CourseMarket courseMarket = marketService.selectById(id);
        AssertUtil.idOnTheShelf(course.getStatus(), "该商品已上架");

        // 上架需要将相关 内容加入到es全文检索中
        CourseDoc courseDoc = new CourseDoc();
        BeanUtils.copyProperties(course, courseDoc);
        CourseType courseType = typeService.selectById(course.getCourseTypeId());
        BeanUtils.copyProperties(courseType,courseDoc);

        courseDoc.setCourseName(course.getName());
        courseDoc.setCourseTypeName(courseType.getName());
        courseDoc.setPrice(courseMarket.getPrice());
        courseDoc.setViewCount(course.getViewCount());

        // id需要在最后再设置, 避免copy覆盖id
        courseDoc.setId(course.getId());

        // 远程调用
        AjaxResult ajaxResult = searchFeginClient.saveCourse(courseDoc);
        AssertUtil.isTrue(ajaxResult.isSuccess(), ajaxResult.getMessage());

        // 上架
        course.setStatus(COURSE_IS_ON_THE_SHELF);
        // 上架后要将相关类型课程的课程数量加1, 上架时间设置

        modifyTheShelf(course.getCourseTypeId(), 1);
        course.setOnlineTime(new Date());
        baseMapper.updateById(course);

        // 消息推送
        newsPush(courseDoc);

    }

    @Value("${rabbitmq.message.sms}")
    private String SMSMessage;
    @Value("${rabbitmq.message.email}")
    private String emailMessage;
    @Value("${rabbitmq.message.message}")
    private String stationmessage;

    private void newsPush(CourseDoc courseDoc) {
        SMSTO smsto = new SMSTO();
        smsto.setMessage(String.format(SMSMessage, courseDoc.getCourseName()));
        smsto.setPhones("1111111");
        rabbitTemplate.convertAndSend(EXCHANGE_NAME_TOPIC, "message.sms", smsto);
        log.info(smsto.toString());
    }

    @Override
    public void offLineCourse(Long id) {
        // 根据课程id 修改数据库中的上限状态(如果是已下架, 不管)
        Course course = baseMapper.selectById(id);
        AssertUtil.idOffTheShelf(course.getStatus(), "该商品已下架");
        // 下架需要将es的干掉
        AjaxResult ajaxResult = searchFeginClient.deleteCourseById(id);
        AssertUtil.isTrue(ajaxResult.isSuccess(), ajaxResult.getMessage());

        // 下架
        course.setStatus(COURSE_IS_NOT_ON_THE_SHELF);
        // 下架后要将相关类型课程的课程数量加-1
        modifyTheShelf(course.getCourseTypeId(), -1);
        course.setOfflineTime(new Date());
        // 保存到数据库
        baseMapper.updateById(course);
    }

    private void modifyTheShelf(Long courseTypeId, Integer quantityChange) {
        // 根据课程类型id, 查询path
        CourseType courseType = typeService.selectById(courseTypeId);
        List<String> types = Arrays.asList(courseType.getPath().split("\\."));

        typeService.updateByIdsToTotalCount(types, quantityChange);

    }
}
